﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.IO;
using smartcrm.Utilities;

namespace smartcrm
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            string FilePath = Path.Combine(Server.MapPath("/"), "log");

            DateTime dt = DateTime.Now;
            String FileName = Path.Combine(FilePath, dt.ToString("yyyyMMdd") + ".txt");
            Exception ex = Server.GetLastError();

            if (ex.GetType() == typeof(NoPermissionException))
            {
                if (!(ex as NoPermissionException).IsJson)
                {
                    Response.Redirect("/Home/Error/1");
                }                
            }
            else if (ex.GetType() == typeof(NoEntityFound))
            {
                Response.Redirect("/Home/Error/2");
            }
            else
            {
                try
                {
                    File.AppendAllText(FileName, string.Format("{0} {1}", "ERROR " + dt.ToString("HH:mm:ss"), ex.Message + "; " + ex.InnerException + "; " + ex.StackTrace + System.Environment.NewLine + System.Environment.NewLine));
                }
                catch
                {
                    //Response.Redirect("/Home/Error/99");
                }
            }
            
        }
       
    }
}